const jwtToken = require('../jwt')
const { expressjwt: jwt } = require('express-jwt')
const config = require('../config')
let whiteList = [
  config.routerFix + '/signIn',
  config.routerFix + '/users/register',
  config.routerFix + '/users/login'
]

function onParseToken(req, res, next) {
  jwt({
    secret: config.jwtSecretkey, // 签名的密钥 或 PublicKey
    algorithms: ['HS256']
  }).unless({
    path: whiteList // 指定路径不经过 Token 解析
  })(req, res, next)
}

function onVerifyToken(err, req, res, next) {
  const authHeader = req.headers['authorization']
  let token = authHeader && authHeader.split(' ')[1] // 格式为 'Bearer token'
  if (!token) {
    return res.rendStatus({ status: 401, err: 'Token is required' })
  }

  if (err.name === 'UnauthorizedError') {
    return res.rendStatus({ status: 401, err: 'Token过期' })
  } else {
    next(err)
  }
}

// 中间件函数，用于记录请求日志
function logRequest(req, res, next) {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`)
  next() // 继续执行下一个中间件
}

function handleCors(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
  )
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  if (req.method === 'OPTIONS') {
    // 处理 OPTION 预检请求
    // res.status(204).end()
    return res.rendStatus({ status: 204, err: '' })
  } else {
    next()
  }
}

module.exports = {
  logRequest,
  handleCors,
  onParseToken,
  onVerifyToken
}
